package com.yuan.zs.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuan.base.framework.BaseAppContext;
import com.yuan.base.framework.http.BaseHttpCallBack;
import com.yuan.base.framework.http.BaseHttpRequest;
import com.yuan.zs.AppContext;
import com.yuan.zs.Urls;
import com.yuan.zs.bean.Child;
import com.yuan.zs.bean.Comment;
import com.yuan.zs.bean.Grade;
import com.yuan.zs.bean.Notice;
import com.yuan.zs.bean.School;
import com.yuan.zs.bean.Wonderful;

import org.xutils.DbManager;
import org.xutils.ex.DbException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 缓存处理类（大部分已弃用）
 */
public class CacheManager {

	private static CacheManager instance;
	private DbManager dbManager;

	private CacheManager() {
	}

	public static CacheManager getInstance() {
		if (instance == null) {
			instance = new CacheManager();
		}
		try {
			if (instance.dbManager == null || instance.dbManager != BaseAppContext.getDbUtils()) {
				instance.dbManager = BaseAppContext.getDbUtils();
			}
		} catch (DbException ignored) {
		}
		return instance;
	}

	public static void destroy() {
		try {
			getInstance().dbManager.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		getInstance().dbManager = null;
		instance = null;
	}

	public void getComment(int pushId, int type, HandleCallback<List<Comment>> callback) {
		HashMap<String, Object> params = new HashMap<>();
		params.put("pushId", pushId);
		params.put("type", type == 1 ? "video" : "image");
		BaseHttpRequest.get(Urls.getUrl(Urls.getCommentList), params, new BaseHttpCallBack<JSONObject>() {
			@Override
			public void onSuccess(JSONObject result) {
				if (result != null && result.containsKey("content")) {
					List<Comment> commentList = JSON.parseArray(result.getString("content"), Comment.class);
					callback.onHttpSuccess(commentList);
				} else {
					callback.onError();
				}
			}

			@Override
			public void onFailure(int code, String msg) {
				callback.onError();
			}
		});

	}

	public void saveChild(List<Child> childList) {
		try {
			dbManager.delete(Child.class);
			dbManager.saveOrUpdate(childList);
		} catch (DbException e) {
			e.printStackTrace();
		}
	}

	// 精彩瞬间列表
	public List<Wonderful> getWonderfulDataByCache(int index, int pageSize) {
		List<Wonderful> result = null;
		try {
			result = dbManager.selector(Wonderful.class)
					.orderBy("time", true)
					.limit(pageSize).offset((index - 1) * pageSize)
					.findAll();
		} catch (DbException e) {
			e.printStackTrace();
		}
		if (result == null) {
			result = new ArrayList<>();
		}
		return result;
	}

	// 精彩瞬间列表
	public void getWonderfulData(int index, int pageSize, boolean needUpdate, HandleCallback<List<Wonderful>> callback) {
		List<Wonderful> result = getWonderfulDataByCache(index, pageSize);
		callback.onCacheSuccess(result);

		// 全量数据刷新缓存
		if (needUpdate) {
			List<Child> childList = getChildList();
			List<Wonderful> allData = new ArrayList<>();
			for (int i = 0; i < childList.size(); i++) {
				int finalI = i;
				initWonderfulData(childList.get(i), new HandleCallback<List<Wonderful>>() {
					@Override
					public void onCacheSuccess(List<Wonderful> result) {
					}

					@Override
					public void onHttpSuccess(List<Wonderful> result) {
						allData.addAll(result);
						if (finalI == childList.size() - 1) {
							try {
								AppContext.getDbUtils().delete(Wonderful.class);
								AppContext.getDbUtils().saveOrUpdate(allData);
								List<Wonderful> temp = getWonderfulDataByCache(index, pageSize);
								// 发生数据变化才去回调http接口
								if (temp.get(0).getId() != result.get(0).getId() || temp.get(0).getType() != result.get(0).getType()) {
									callback.onHttpSuccess(allData);
								}
							} catch (DbException e) {
								e.printStackTrace();
								callback.onError();
							}
						}
					}

					@Override
					public void onError() {
						callback.onError();
					}
				});
			}
		}
	}

	private void initWonderfulData(Child child, HandleCallback<List<Wonderful>> callback) {
		HashMap<String, Object> params = new HashMap<>();
		params.put("childIdCardNo", child.getIdCardNo());
		BaseHttpRequest.get(Urls.getUrl(Urls.getWonderfulVideoList), params, new BaseHttpCallBack<JSONObject>() {

			@Override
			public void onSuccess(JSONObject videoResult) {
				if (videoResult != null && videoResult.containsKey("content")) {
					List<Wonderful> videoList = JSON.parseArray(videoResult.getString("content"), Wonderful.class);
					for (int i = 0; i < videoList.size(); i++) {
						videoList.get(i).setType(1);
					}
					HashMap<String, Object> params = new HashMap<>();
					params.put("childIdCardNo", child.getIdCardNo());
					BaseHttpRequest.get(Urls.getUrl(Urls.getWonderfulImageList), params, new BaseHttpCallBack<JSONObject>() {

						@Override
						public void onSuccess(JSONObject imgResult) {
							if (imgResult != null && imgResult.containsKey("content")) {
								List<Wonderful> imageList = JSON.parseArray(videoResult.getString("content"), Wonderful.class);
								for (int i = 0; i < imageList.size(); i++) {
									imageList.get(i).setType(2);
								}
								videoList.addAll(imageList);
								callback.onHttpSuccess(videoList);
							} else {
								callback.onError();
							}
						}

						@Override
						public void onFailure(int code, String msg) {
							callback.onError();
						}
					});

				} else {
					callback.onError();
				}
			}

			@Override
			public void onFailure(int code, String msg) {
				callback.onError();
			}
		});

	}

	// 获取孩子缓存
	public List<Child> getChildList() {
		List<Child> result = null;
		try {
			result = dbManager.findAll(Child.class);
		} catch (DbException e) {
			e.printStackTrace();
		}
		if (result == null) {
			result = new ArrayList<>();
		}
		return result;
	}

	// 删除缓存中的某个孩子
	public void deleteChild(int id) {
		try {
			dbManager.deleteById(Child.class, id);
		} catch (DbException e) {
			e.printStackTrace();
		}
	}

	// 获取通知内容
	public void initNotificationData(HandleCallback<List<Notice>> callback) {
		BaseHttpRequest.get(Urls.getUrl(Urls.getNotificationAllList), new BaseHttpCallBack<JSONObject>() {

			@Override
			public void onSuccess(JSONObject result) {
				if (result != null && result.containsKey("content")) {
					try {
						List<Notice> noticeList = JSON.parseArray(result.getString("content"), Notice.class);
						AppContext.getDbUtils().delete(Notice.class);
						AppContext.getDbUtils().saveOrUpdate(noticeList);
						callback.onHttpSuccess(noticeList);
					} catch (DbException e) {
						e.printStackTrace();
						callback.onError();
					}
				} else {
					callback.onError();
				}
			}

			@Override
			public void onFailure(int code, String msg) {
				callback.onError();
			}
		});
	}

	// 查询通知列表
	public List<Notice> getNoticeList(int type, int index, int pageSize) {
		List<Notice> result = null;
		try {
			result = dbManager.selector(Notice.class)
					.where("type", "=", type)
					.orderBy("publishDate", true)
					.limit(pageSize).offset((index - 1) * pageSize)
					.findAll();
		} catch (DbException e) {
			e.printStackTrace();
		}
		if (result == null) {
			result = new ArrayList<>();
		}
		return result;
	}

	// 获取指定学校信息
	public void getSchool(int schoolId, HandleCallback<School> callback) {
		try {
			School school = dbManager.findById(School.class, schoolId);
			if (school != null) {
				callback.onCacheSuccess(school);
				return;
			}
		} catch (DbException e) {
			e.printStackTrace();
		}

		BaseHttpRequest.get(Urls.getUrl(Urls.getSchoolById + schoolId), new BaseHttpCallBack<School>() {

			@Override
			public void onSuccess(School result) {
				if (result != null) {
					callback.onHttpSuccess(result);
					try {
						dbManager.saveOrUpdate(result);
					} catch (DbException e) {
						e.printStackTrace();
					}
				} else {
					callback.onError();
				}
			}

			@Override
			public void onFailure(int code, String msg) {
				callback.onError();
			}
		});
	}

	// 获取指定班级信息
	public void getGrade(int schoolId, int gradeId, HandleCallback<Grade> callback) {
		try {
			Grade grade = dbManager.findById(Grade.class, gradeId);
			if (grade != null) {
				callback.onCacheSuccess(grade);
				return;
			}
		} catch (DbException e) {
			e.printStackTrace();
		}

		HashMap<String, Object> params = new HashMap<>();
		params.put("school", schoolId);
		BaseHttpRequest.get(Urls.getUrl(Urls.getGradeById), params, new BaseHttpCallBack<List<Grade>>() {

			@Override
			public void onSuccess(List<Grade> result) {
				if (result != null) {
					Grade grade = null;
					for (int i = 0; i < result.size(); i++) {
						if (gradeId == result.get(i).getId()) {
							grade = result.get(i);
							callback.onHttpSuccess(grade);
						}
					}
					if (grade == null) {
						callback.onError();
					}
					try {
						dbManager.saveOrUpdate(result);
					} catch (DbException e) {
						e.printStackTrace();
					}
				} else {
					callback.onError();
				}
			}

			@Override
			public void onFailure(int code, String msg) {
				callback.onError();
			}
		});
	}

	public interface HandleCallback<T> {
		void onCacheSuccess(T result);

		void onHttpSuccess(T result);

		void onError();
	}

}
